package com.framewiki.example.service.impl;

import com.cdkjframework.config.CustomConfig;
import com.cdkjframework.constant.CacheConsts;
import com.cdkjframework.constant.IntegerConsts;
import com.cdkjframework.core.member.CurrentUser;
import com.cdkjframework.entity.PageEntity;
import com.cdkjframework.entity.user.UserEntity;
import com.cdkjframework.enums.UserTypeEnums;
import com.cdkjframework.exceptions.GlobalRuntimeException;
import com.cdkjframework.redis.RedisUtils;
import com.cdkjframework.redis.lock.impl.RedisLettuceLock;
import com.cdkjframework.util.encrypts.JwtUtils;
import com.cdkjframework.util.encrypts.Md5Utils;
import com.cdkjframework.util.log.LogUtils;
import com.cdkjframework.util.tool.CopyUtils;
import com.cdkjframework.util.tool.StringUtils;
import com.cdkjframework.util.tool.number.ConvertUtils;
import com.framewiki.example.dto.RmsUserDto;
import com.framewiki.example.entity.RmsUserEntity;
import com.framewiki.example.entity.extend.RmsUserExtendEntity;
import com.framewiki.example.mapper.RmsUserMapper;
import com.framewiki.example.service.RmsUserService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ProjectName: com.lesmarthome.bms
 * @Package: com.lesmarthome.bms
 * @ClassName: RmsUser
 * @Description: 登录用户
 * @Author: DESKTOP-U0VVSVK
 * @Version: 1.0
 */

@Service
@RequiredArgsConstructor
public class RmsUserServiceImpl implements RmsUserService {

  /**
   * 日志
   */
  private static final LogUtils logUtil = LogUtils.getLogger(RmsUserServiceImpl.class);

  /**
   * 登录用户 mapper
   */
  private final RmsUserMapper rmsUserMapper;

  /**
   * 修改用户信息
   *
   * @param rmsUserDto 登录用户 - 实体
   * @throws GlobalRuntimeException 异常信息
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void modifyRmsUser(RmsUserDto rmsUserDto) {
    UserEntity currentUser = CurrentUser.getCurrentUser();
    // 检查是否修改了登录账号
    RmsUserEntity rmsUserEntity = rmsUserMapper.findEntityById(rmsUserDto.getId());
    if (rmsUserEntity == null || StringUtils.isNullAndSpaceOrEmpty(rmsUserEntity.getId())) {
      throw new GlobalRuntimeException("未查询到该账号！");
    }
    if (StringUtils.isNullAndSpaceOrEmpty(rmsUserDto.getLoginName())) {
      rmsUserDto.setLoginName(rmsUserEntity.getLoginName());
    }
    if (!rmsUserDto.getLoginName().equals(rmsUserEntity.getLoginName())) {
      throw new GlobalRuntimeException("登录账号不能进行修改！");
    }
    // 检查是否修改了人脸识别码
    if (StringUtils.isNotNullAndEmpty(rmsUserDto.getFaceCode())) {
      RmsUserEntity userEntity = new RmsUserEntity();
      userEntity.setFaceCode(rmsUserDto.getFaceCode());
      List<RmsUserEntity> userEntities = rmsUserMapper.listFindByEntity(userEntity);
      if (!CollectionUtils.isEmpty(userEntities)) {
        List<RmsUserEntity> modifyList = userEntities.stream().filter(f -> !f.getId().equals(rmsUserDto.getId())).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(modifyList)) {
          modifyList.stream().forEach(f -> {
            f.setFaceCode(StringUtils.Empty);
            f.setEditTime(LocalDateTime.now());
            f.setEditUserId(currentUser.getId());
            f.setEditUserName(currentUser.getDisplayName());
          });
          rmsUserMapper.modifyBatch(modifyList);
        }
      }
    }
    rmsUserDto.setEditTime(LocalDateTime.now());
    rmsUserDto.setEditUserId(CurrentUser.getUserId());
    rmsUserDto.setEditUserName(CurrentUser.getRealName());
    RmsUserEntity entity = CopyUtils.copyProperties(rmsUserDto, RmsUserEntity.class);
    //如果是网点客户修改网点
    if (StringUtils.isNotNullAndEmpty(rmsUserDto.getSuperiorOrganizationId())) {
      entity.setCurrentOrganizationId(rmsUserDto.getSuperiorOrganizationId());
    }
    rmsUserMapper.modify(entity);
  }

  /**
   * 添加员工账户数据
   *
   * @param rmsUserDto 登录用户 - 实体
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void addRmsUser(RmsUserDto rmsUserDto) {

    // step3 检查账户是否重复
    Integer number = rmsUserMapper.existsLoginName(rmsUserDto.getLoginName());
    if (number > 0) {
      throw new GlobalRuntimeException("账号已存在，请更换账号！");
    }
  }

  /**
   * 删除数据
   *
   * @param rmsUserDto 登录用户 - 实体
   */
  @Override
  public void deleteRmsUser(RmsUserDto rmsUserDto) {
    RmsUserEntity entity = CopyUtils.copyProperties(rmsUserDto, RmsUserEntity.class);
    rmsUserMapper.delete(entity);
  }

  /**
   * 查询分页数据
   *
   * @param rmsUserDto 查询实体
   * @return 返回分页数据实体
   */
  @Override
  public PageEntity<RmsUserDto> listRmsUserPage(RmsUserDto rmsUserDto) {
    boolean ifRoleAdmin = false;
    if (!ifRoleAdmin) {
      rmsUserDto.setTopOrganizationId(StringUtils.isNotNullAndEmpty(rmsUserDto.getTopOrganizationId()) ? rmsUserDto.getTopOrganizationId() : CurrentUser.getTopOrganizationId());
    } else {
      rmsUserDto.setUserType(UserTypeEnums.SUPER.getValue());
    }
    //返回对象
    PageEntity<RmsUserDto> pageEntity = new PageEntity<>();

    //分页查询角色信息
    Page<RmsUserExtendEntity> page = PageHelper.startPage(rmsUserDto.getPageIndex(), rmsUserDto.getPageSize());

    // 账户采用模糊查询
    rmsUserDto.setVagueFlag(IntegerConsts.ONE);
    //对象转换 dto -> entity
    RmsUserExtendEntity entity = CopyUtils.copyProperties(rmsUserDto, RmsUserExtendEntity.class);
    List<RmsUserExtendEntity> extendEntities = rmsUserMapper.listFindRmsUser(entity);

    pageEntity.setPageIndex(rmsUserDto.getPageIndex());
    pageEntity.setTotal(page.getTotal());

    // 查询用户角色信息
    List<RmsUserDto> userDtos = CopyUtils.copyProperties(extendEntities, RmsUserDto.class);

    pageEntity.setData(userDtos);

    //返回分页数据
    return pageEntity;
  }

  /**
   * 查询分页数据
   *
   * @param rmsUserDto 查询实体
   * @return 返回分页数据实体
   */
  @Override
  public List<RmsUserDto> listRmsUser(RmsUserDto rmsUserDto) {
    return null;
  }
}
